package com.waves.message.listeners;

import com.rabbitmq.client.Channel;
import com.waves.core.message.MessageTransfer;
import com.waves.core.utils.JsonUtils;
import com.waves.message.model.SendMessageModel;
import com.waves.message.service.SendMessageService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Objects;

/**
 * @author wangzhiwei
 * @date 2023/10/29 09:08
 **/
@Component
@Slf4j
@RequiredArgsConstructor
public class MessageRabbitListener {

    private final SendMessageService sendMessageService;

    @RabbitListener(queues = "messageTemplate", ackMode = "MANUAL")
    public void batchConsumer(String messageStr, Channel channel,
                              MessageProperties messageProperties) throws IOException {

        try {
            MessageTransfer messageTransfer = JsonUtils.parseObject(messageStr,
                                                                    MessageTransfer.class);
            if (Objects.isNull(messageTransfer)) {
                log.warn("批量推送消息失败,messageStr:{}", messageStr);
                return;
            }

            SendMessageModel sendMessageModel = new SendMessageModel();
            BeanUtils.copyProperties(messageTransfer, sendMessageModel);
            sendMessageService.sendMessage(sendMessageModel);

            channel.basicAck(messageProperties.getDeliveryTag(), false);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            channel.basicReject(messageProperties
                                        .getDeliveryTag(), true);
        }
    }


}
